package cn.lovemmd.model.mapper;

import cn.lovemmd.model.entity.DownloadLog;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.util.List;
import java.util.Map;

@Mapper
public interface DownloadLogMapper extends BaseMapper<DownloadLog> {
    
    @Select("SELECT COUNT(*) FROM model_download_log WHERE deleted = 0")
    Long countTotalDownloads();
    
    @Select("SELECT COUNT(*) FROM model_download_log WHERE deleted = 0 AND created_at >= DATE_SUB(NOW(), INTERVAL 1 DAY)")
    Long countDownloadsLast24h();
    
    @Select("SELECT COUNT(*) FROM model_download_log WHERE deleted = 0 AND created_at >= DATE_SUB(NOW(), INTERVAL 7 DAY)")
    Long countDownloadsLast7d();
    
    @Select("SELECT COUNT(*) FROM model_download_log WHERE deleted = 0 AND created_at >= DATE_SUB(NOW(), INTERVAL 30 DAY)")
    Long countDownloadsLast30d();
    
    @Select("SELECT COUNT(*) FROM model_download_log WHERE deleted = 0 AND model_id = #{modelId}")
    Long countDownloadsByModelId(@Param("modelId") Long modelId);
    
    @Select("SELECT COUNT(*) FROM model_download_log WHERE deleted = 0 AND model_id = #{modelId} AND created_at >= DATE_SUB(NOW(), INTERVAL 1 DAY)")
    Long countDownloadsByModelIdLast24h(@Param("modelId") Long modelId);
    
    @Select("SELECT COUNT(*) FROM model_download_log WHERE deleted = 0 AND model_id = #{modelId} AND created_at >= DATE_SUB(NOW(), INTERVAL 7 DAY)")
    Long countDownloadsByModelIdLast7d(@Param("modelId") Long modelId);
    
    @Select("SELECT COUNT(*) FROM model_download_log WHERE deleted = 0 AND model_id = #{modelId} AND created_at >= DATE_SUB(NOW(), INTERVAL 30 DAY)")
    Long countDownloadsByModelIdLast30d(@Param("modelId") Long modelId);
    
    @Select("SELECT ml.m_name, COUNT(dl.id) as download_count FROM model_download_log dl " +
            "LEFT JOIN model_list ml ON dl.model_id = ml.m_id " +
            "WHERE dl.deleted = 0 AND ml.deleted = 0 " +
            "GROUP BY dl.model_id, ml.m_name " +
            "ORDER BY download_count DESC LIMIT #{limit}")
    List<Map<String, Object>> selectTopDownloadedModels(@Param("limit") int limit);
    
    @Select("SELECT DATE(created_at) as date, COUNT(*) as count FROM model_download_log " +
            "WHERE deleted = 0 AND created_at >= DATE_SUB(NOW(), INTERVAL 30 DAY) " +
            "GROUP BY DATE(created_at) ORDER BY date")
    List<Map<String, Object>> selectDownloadTrend();
    
    @Select("SELECT * FROM model_download_log WHERE deleted = 0 ORDER BY created_at DESC LIMIT #{limit}")
    List<DownloadLog> selectRecentDownloads(@Param("limit") int limit);
}
